/*
 * @Author: Jiraiya
 * @Date: 2020-05-06 14:30:44
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-05-07 11:08:15
 * @Description: 
 */

const path = require('path')
const utils = require('./utils')
const debug = require('debug')('/src/core/Loader');

class Loader{

    constructor({root, env}){
        this.root = root;
        this.env = env;
        
        this.filePattern = {
            systemConfig: [
                `/src/config/config.js`,
                `/src/config/config.${this.env}.js`
            ],
            definition: {
                middleware: '/src/middleware/*.js',
                service: '/src/server/*.js',
                plugin: '/src/plugin/*.js'
            }
        }
    }

    
    /**
     * @description: 加载系统配置
     * @param {type} 
     * @returns {Object}
     */
    loadSystemConfig(){
        const files = utils.findFiles(this.root, this.filePattern.systemConfig);
        return utils.mergeConfigFiles(files);
    }

    /**
     * @description: 加载插件
     * @param {type} 
     * @returns {Object}
     */
    loadPlugin(){
        const files = utils.findFiles(this.root, this.filePattern.definition.plugin);
        return utils.mergeConfigFiles(files);
    }

    /**
     * @description: 收集所有的中间件的位置
     * @param {type} 
     * @returns {Map}
     */
    loadMiddleware(){
        const middlewareMap = new Map();
        let files = utils.findFiles(this.root, this.filePattern.definition.middleware);
        files.forEach((filePath) => {
            //middleware的文件名作为名字
            const name = path.basename(filePath, '.js');
            if(middlewareMap.has(name)){
                debug(`发现同名的middleware [%s] 被替换的是[%s]  优先级更高的是[%s]`, name, middlewareMap.get(name), filePath);
            }
            middlewareMap.set(name, filePath);
        });
        return middlewareMap;
    }


    /**
     * @description: 收集后端服务并配置
     * @param {type} 
     * @returns {Map}
     */
    loadService(){
        let serviceMap = new Map();
        let files = utils.findFiles(this.root, this.filePattern.definition.service);
        files.forEach((filePath) => {
            // 文件名为服务器名
            const name = path.basename(filePath, '.js');
            if(serviceMap.has(name)){
                debug(`发现同名的 service [%s] 被替换的是[%s]  优先级更高的是[%s]`, name, serviceMap.get(name), filePath);
            }
            serviceMap.set(name, filePath);
        });

        let out = new Map();
        for(let [key, val] of serviceMap){
            out.set(key, require(val));
        }

        return out;
    }

    
}

module.exports = Loader;